package br.ufg.inf.espweb.sgca.dao.impl;

import br.ufg.inf.espweb.sgca.dao.PessoaDao;
import br.ufg.inf.espweb.sgca.dao.UsuarioDao;
import br.ufg.inf.espweb.sgca.model.Usuario;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author diCastro
 */
@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class UsuarioDaoImpl extends GenericDaoImpl<Usuario> implements UsuarioDao{
    
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private PessoaDao pessoaDao;
    
    @Override
    protected EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    protected Class<Usuario> getEntityClass() {
        return Usuario.class;
    }

    @Override
    public Usuario buscarUsuarioPorUserName(String username) {
        Criteria criteria = getSession().createCriteria(Usuario.class);
        criteria.add(Restrictions.eq("username", username));
        criteria.setMaxResults(1);
        return (Usuario) criteria.uniqueResult();
    }

    @Override
    public void salvar(Usuario usuario) {
        if(usuario != null){
            if(usuario.getPessoa() != null && usuario.getPessoa().getId() == null){
                pessoaDao.salvar(usuario.getPessoa());
            }
            super.salvar(usuario);
        }
        
    }
}
